import React, { Component } from 'react'
import { routerRedux } from 'dva/router'
import { connect } from 'dva'
import { message } from 'antd'
import { request, config } from 'utils'
import Eloam from '../../../components/Eloam/index'
import EditForm from './addNaturalPersonModal'
import CrossBrowserDriver from '../../../components/CrossBrowserDriver/index'
const { host, fileSource, api: { orgOCR } } = config

class OrgForm extends Component {
  constructor(props) {
    super(props)
    this.state = {
      fileList: {},
      orgData: {},
      fullState: {
        assetsInfoState: 0,
        otherInfoState:0,
      },
      isNew:true
    }
    this.type = 0
    this.pictureType = 0
  }

  onBarcodeDecode(data) {
    if (!data) {
      message.error("二维码识别失败", 5);
      return
    }
    this.setState({ orgData: data })
  }
  getCaption(obj,state) {
    var index=obj.lastIndexOf("\-");
    if(state==0){
        obj=obj.substring(0,index);
    }else {
        obj=obj.substring(index+1,obj.length);
    }
    return obj;
}
  onUploadChange({ file, fileList, key }) {
    if (file.status == "removed") {
      if (file.response) {
        this.props.dispatch({
          type: 'client/deleteImgModels',
          payload: {
            fileId:file.response.fileId
          }
        })
      } else {
        let fileID = file.url.substring(file.url.lastIndexOf("\/") + 1, file.url.length)
        if(fileID.indexOf("?") != -1){
          let fileIDFinal = fileID.substring(0,fileID.lastIndexOf('?'))
          this.props.dispatch({
            type: 'client/deleteImgModels',
            payload: {
              fileId:fileIDFinal
            }
          })
        }else{
          this.props.dispatch({
            type: 'client/deleteImgModels',
            payload: {
              fileId:fileID
            }
          })
        }
      }
    }
    const files = this.state.fileList
    if (file.status === 'done') {
      const { response } = file
      if (response.code) {
        message.error("文件上传失败:" + response.msg, 5);
        fileList[fileList.length - 1]["status"] = "error"
      }
    }
    files[key] = fileList
    this.setState({ fileList: files })
  }
  onTakePicture(type) {

    this.pictureType = type
    const localId = sessionStorage.getItem("localId")
    const userId = sessionStorage.getItem('userId')
    this.refs.crossBrowserDriver.openVideoMain(0, {
      userId,
      localId,
      partyNumber: 0,
      type: 1,
      dataType: type
    })
  }
  onTakePictureBase64() {
    this.refs.crossBrowserDriver.openVideoMain(3,{})
  }
  onSwitchChange(val, key) {
    const fullState = this.state.fullState
    if (val) {
      fullState[key] = 1
    } else {
      fullState[key] = 0
    }
    this.setState({ fullState: fullState })
  }
  fecthOrgData(base64) {
    const url = host + orgOCR
    const hide = message.loading('正在识别中', 0);
    request({
      url,
      data: {
        imageBaseStr: base64
      },
      method: 'POST',
    }).then(response => {
      hide()
      const { code, message, result } = response
      if (code) {
        message.error(code + ":" + message, 5)
        return
      }
      const data = JSON.parse(result)
      const orgData = {
        img: base64,
        name: data['单位名称']['words'],
        creditCode: data['社会信用代码']['words'],
        type: data['类型']['words'],
        address: data['地址']['words'],
        legalPerson: data['法人']['words'],
        registeredCapital: data['注册资本']['words'],
        establishmentTime: data['成立日期']['words'],
        businessTerm: data['有效期']['words'],
        businessScope: data['经营范围']['words'],
      }
      this.setState({
        orgData
      })
    }).catch(e => {

      hide()
      let msg = "网络请求失败"
      if (e.message) {
        msg = JSON.parse(e.message)["msg"] || msg
      }
      message.error(msg, 5)
    })
  }
  addThePartORG(payload) {
    this.props.dispatch({
      type: "org/addTheORG",
      payload: payload
    })
  }
  pushToPeople() {
    this.props.dispatch(routerRedux.push({
      pathname: "/app/client",
    }))
  }
  readBarcode() {
    this.refs.crossBrowserDriver.openVideoMain(2)
  }
  makeFile(files) {
    let currentTime ='?timestamp='+ new Date().getTime()
    let newArry = []
    files.map((item,index) => {
      newArry.push(
        {
          uid:index,
          name:index+'xxx.png',
          url:fileSource+item+currentTime
        }
      )
    })
    return newArry
  }
  componentDidMount() {
    const { location, dispatch, org, loading } = this.props
    if (org.isNew) {
      sessionStorage.setItem("localId", new Date().getTime())
    } else {
      // console.log(org.currentInfo)
      let currentTime ='?timestamp='+ new Date().getTime()
      sessionStorage.setItem("localId",org.currentInfo.appPartyUser.localId)
      let files = {}
      let fileArry0 = [org.currentInfo.partyFile["1"]]
      let fileArry1 = [org.currentInfo.partyFile["2"]]
      files["1"] = this.makeFile(fileArry0["0"])
      files["2"] = this.makeFile(fileArry1["0"])
      this.setState({
        orgData: {
          img: org.currentInfo.appPartyUser.businessLicenseFileUrl!=''&& org.currentInfo.appPartyUser.businessLicenseFileUrl!=null?fileSource + org.currentInfo.appPartyUser.businessLicenseFileUrl+currentTime:'',
          name: org.currentInfo.appPartyUser.name,
          creditCode: org.currentInfo.appPartyUser.creditCode,
          type: org.currentInfo.appPartyUser.type,
          address: org.currentInfo.appPartyUser.address,
          legalPerson: org.currentInfo.appPartyUser.legalPerson,
          registeredCapital: org.currentInfo.appPartyUser.registeredCapital,
          establishmentTime: org.currentInfo.appPartyUser.establishmentTime,
          businessTerm: org.currentInfo.appPartyUser.businessTerm,
          businessScope: org.currentInfo.appPartyUser.businessScope,
          mobile: org.currentInfo.appPartyUser.mobile,
          email: org.currentInfo.appPartyUser.email,
          legalPersonId: org.currentInfo.appPartyUser.legalPersonId,
          clientId: org.currentInfo.appPartyUser.clientId,
        },
        fileList: files,
        isNew:false,
        fullState: {
          assetsInfoState:org.currentInfo.appPartyUser.assetsInfoState,
          otherInfoState:org.currentInfo.appPartyUser.otherInfoState,
        }
      })
    }
  }
  toBack() {
    this.props.dispatch({
      type: "org/backIndex",
      payload: {
      }
    })
  };
  resetData() {
    sessionStorage.setItem("localId", new Date().getTime())
    this.setState({
      fileList: {},
      orgData: {},
      fullState: {
        assetsInfoState: 0,
        otherInfoState:0,
      }
    })
  }
  render() {
    const { location, dispatch, org, loading } = this.props
    const { fileList, orgData,fullState,isNew} = this.state
    const { naturePeople } = org
    const formProps = {
      addThePartORG: (data) => this.addThePartORG(data),
      readBarcode: () => this.readBarcode(),
      pushToPeople: () => this.pushToPeople(),
      onTakePicture: (type) => this.onTakePicture(type),
      onTakePictureBase64: () => this.onTakePictureBase64(),
      onUploadChange: ({ file, fileList, key }) => this.onUploadChange({ file, fileList, key }),
      naturePeople,
      orgData,
      fileList,
      fullState,
      isNew,
      toBack: () => this.toBack(),
      onSwitchChange: (val, key) => this.onSwitchChange(val, key),
      resetData: () =>this.resetData(),
    }

    return (
      <div style={{ overflow: 'auto' }}>

        <EditForm {...formProps} />
        <CrossBrowserDriver ref="crossBrowserDriver"
          onBarcodeDecode={(data) => {
            this.onBarcodeDecode(data)
          }}
          onAssistPicture={(base64) => {

          }}
          onTakePictureBase64={(base64) => {
            this.fecthOrgData(base64)
          }}
          onTakePicture={(info) => {
            let a = info.json()
            a.then(obj => {
              const { fileList } = this.state
              let infoJSON = {}
              try {
                infoJSON = obj
              } catch (e) {
                message.error("服务器返回数据格式异常", 3);
                return
              }
              if (!infoJSON.fileId) {
                message.error(infoJSON.msg || "文件上传失败", 3);
                return
              }
              const url = fileSource + infoJSON.fileId
              const list = fileList[String(this.pictureType)] || []
              list.push({
                uid: new Date().getTime(),
                name: infoJSON.fileId,
                status: 'done',
                url: url
              })
              fileList[String(this.pictureType)] = list
              this.setState({
                fileList,
              })
            })
          }} />
      </div>
    )
  }
}

export default connect(({ org, loading }) => ({ org, loading }))(OrgForm)
